﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using DevExpress.Utils;
using System.IO;

using DevExpress.XtraEditors.Controls;
namespace QLTV.Forms.KhaiBao
{
    public partial class frmCrew : BaseForm
    {
        public frmCrew()
        {
            InitializeComponent();
        }
        public bool isNew { get; set; }
        public string crewid { get; set; }
        public string newCrewid { get; set; }



        private void tblCrewBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            //this.Validate();
            //this.tblCrewBindingSource.EndEdit();
            //this.tableAdapterManager.UpdateAll(this.dsCrew);

        }

        private void frmCrew_Load(object sender, EventArgs e)
        {

            // TODO: This line of code loads data into the 'dsCrew.tblRank' table. You can move, or remove it, as needed.
            this.tblRankTableAdapter.Fill(this.dsCrew.tblRank);
            // TODO: This line of code loads data into the 'dsRanking.tblRank' table. You can move, or remove it, as needed.

            // TODO: This line of code loads data into the 'dsVessel.tblEngineType' table. You can move, or remove it, as needed.
            this.tblEngineTypeTableAdapter.Fill(this.dsVessel.tblEngineType);
            // TODO: This line of code loads data into the 'dsVessel.tblEngineMaker' table. You can move, or remove it, as needed.
            this.tblEngineMakerTableAdapter.Fill(this.dsVessel.tblEngineMaker);
            // TODO: This line of code loads data into the 'dsVessel.tblVesselType' table. You can move, or remove it, as needed.
            this.tblVesselTypeTableAdapter.Fill(this.dsVessel.tblVesselType);
            // TODO: This line of code loads data into the 'dsVessel.tblFlag' table. You can move, or remove it, as needed.
            this.tblFlagTableAdapter.Fill(this.dsVessel.tblFlag);

            // TODO: This line of code loads data into the 'dsVessel.tblVessel' table. You can move, or remove it, as needed.
            this.tblVesselTableAdapter.Fill(this.dsVessel.tblVessel);
            // TODO: This line of code loads data into the 'dsCrew.tblExprience' table. You can move, or remove it, as needed.

            // TODO: This line of code loads data into the 'dsCrew.tblCertification' table. You can move, or remove it, as needed.
            this.tblCertificationTableAdapter.Fill(this.dsCrew.tblCertification);
            // TODO: This line of code loads data into the 'dsCrew.tblCourse' table. You can move, or remove it, as needed.
            this.tblCourseTableAdapter.Fill(this.dsCrew.tblCourse);
            // TODO: This line of code loads data into the 'dsCrew.tblEducationType' table. You can move, or remove it, as needed.
            this.tblEducationTypeTableAdapter.Fill(this.dsCrew.tblEducationType);
            // TODO: This line of code loads data into the 'dsCrew.tblImmigrationDoc' table. You can move, or remove it, as needed.
            this.tblImmigrationDocTableAdapter.Fill(this.dsCrew.tblImmigrationDoc);
            // TODO: This line of code loads data into the 'dsCrew.tblImmigrationCrew' table. You can move, or remove it, as needed.
            this.tblCrewTypeTableAdapter.Fill(this.dsCrew.tblCrewType);
            // TODO: This line of code loads data into the 'dsCrew.tblCrew' table. You can move, or remove it, as needed.
            if (isNew)
                tblCrewBindingSource.AddNew();
            else
            {
                this.tblCrewTableAdapter.FillByID(this.dsCrew.tblCrew, crewid);
                loadData();

            }
        }

        public string getCrewID()
        {

            if (tblCrewTableAdapter.GetData().Rows.Count > 0)
            {
                var data = from crew in tblCrewTableAdapter.GetData().AsEnumerable()
                           orderby crew.Field<string>("nCrewId").Substring(1) descending
                           select crew.Field<string>("nCrewId").Substring(1);

                int maxID = Convert.ToInt32(data.First<string>());

                if (maxID > 0 && maxID < 10)
                {
                    return "000" + (maxID + 1).ToString();

                }
                if (maxID >= 10 && maxID < 100)
                {
                    return "00" + (maxID + 1).ToString();

                }
                if (maxID >= 100 && maxID < 1000)
                {
                    return "0" + (maxID + 1).ToString();

                }
                if (maxID >= 1000)
                {
                    return maxID.ToString();

                }
            }
            else
                return "0001";
            return "";
        }

        private void updateSource()
        {
            try
            {

                tblCrewBindingSource.EndEdit();
                tblImmigrationCrewBindingSource.EndEdit();
                tblEducationBindingSource.EndEdit();
                tblNhanXetCuaChuTauBindingSource.EndEdit();
                tblExprienceBindingSource.EndEdit();
                tblCertificateCrewBindingSource.EndEdit();

                tblCrewTableAdapter.Update(dsCrew.tblCrew);
                tblImmigrationCrewTableAdapter.Update(dsCrew.tblImmigrationCrew);
                tblEducationTableAdapter.Update(dsCrew.tblEducation);
                tblCertificateCrewTableAdapter.Update(dsCrew.tblCertificateCrew);
                tblNhanXetCuaChuTauTableAdapter.Update(dsCrew.tblNhanXetCuaChuTau);
                tblExprienceTableAdapter.Update(dsCrew.tblExprience);

                tblRankingTableAdapter.Insert(Convert.ToInt32(lookupRan.EditValue), txtMaThuyenVien.Text, (DateTime)dateIssued.EditValue);
                alertControl1.Show(this, "Thông báo", "Cập nhật thành công");

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Đã có lỗi xảy ra" + ex.ToString(), "Thông báo");
            }

        }

        private void loadData()
        {

            this.tblImmigrationCrewTableAdapter.FillByCrewID(this.dsCrew.tblImmigrationCrew, crewid);
            this.tblEducationTableAdapter.FillByCrewID(dsCrew.tblEducation, crewid);
            this.tblCertificateCrewTableAdapter.FillByCrewID(dsCrew.tblCertificateCrew, crewid);
            this.tblNhanXetCuaChuTauTableAdapter.FillByCrewID(dsCrew.tblNhanXetCuaChuTau, crewid);
            this.tblExprienceTableAdapter.FillBy(this.dsCrew.tblExprience, crewid);

            this.tblRankingTableAdapter.FillByCrewID(this.dsCrew.tblRanking, crewid);

        }
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            updateSource();
            dsCrew.AcceptChanges();
            this.Close();
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void lookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (lookUpEdit1.GetColumnValue("Prefix") != null)
            {
                if (isNew)
                    txtMaThuyenVien.EditValue = lookUpEdit1.GetColumnValue("Prefix").ToString().Trim() + newCrewid;
                else
                    txtMaThuyenVien.EditValue = lookUpEdit1.GetColumnValue("Prefix").ToString().Trim() + crewid.Substring(1);
                //tblRankTableAdapter.FillByType(dsCrew.tblRank, Convert.ToInt32(lookUpEdit1.GetColumnValue("id").ToString().Trim()));
                // tblRankTableAdapter.FillByType(dsRanking.tblRank, );
            }
        }

        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (txtMaThuyenVien.Text != "")
            {
                updateSource();
                newCrewid = getCrewID();
                isNew = true;
                crewid = newCrewid;
                tblCrewBindingSource.AddNew();
                loadData();
            }
            else
            {
                // dxErrorProvider1.SetError(lookUpEdit1, "This value is not valid");
                lookUpEdit1.Focus();
            }
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            viewHoChieu.SetRowCellValue(e.RowHandle, viewHoChieu.Columns["nCrewId"], txtMaThuyenVien.EditValue.ToString());
            //dsCrew.AcceptChanges();

        }

        private void viewEducation_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            viewEducation.SetRowCellValue(e.RowHandle, viewEducation.Columns["cCrewID"], txtMaThuyenVien.EditValue.ToString());

        }

        private void viewCertificate_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            viewCertificate.SetRowCellValue(e.RowHandle, viewCertificate.Columns["nCrewid"], txtMaThuyenVien.EditValue.ToString());
        }
        #region Nhan xet cua chu tau

        OpenFileDialog dialogFile;
        byte[] bnoidung;

        private void filePath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            dialogFile = new OpenFileDialog();
            if (dialogFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                bnoidung = ReadFile(dialogFile.FileName);
                ((DevExpress.XtraEditors.ButtonEdit)sender).EditValue = dialogFile.SafeFileName;
            }
        }
        public byte[] ReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                int length = (int)fileStream.Length;
                buffer = new byte[length];
                int count;
                int sum = 0;


                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }
        private void viewNhanXet_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {


        }

        private void viewNhanXet_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["nCrewID"], txtMaThuyenVien.EditValue.ToString());
            FileInfo info = new FileInfo(dialogFile.FileName);
            viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["cExt"], info.Extension);
            viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["nSize"], info.Length / 1000);
            viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["pNoiDung"], bnoidung);

            //   colpNoiDung
        }


        private void xoa_ButtonClick(object sender, ButtonPressedEventArgs e)
        {

            if (viewNhanXet.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblNhanXetCuaChuTauBindingSource.RemoveCurrent();
                    tblNhanXetCuaChuTauTableAdapter.Update(dsCrew.tblNhanXetCuaChuTau);
                    alertControl1.Show(this, "Thông báo", "Xóa thành công");
                }
            }
        }

        private void btnXem_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewNhanXet.FocusedRowHandle > -1)
            {
                SaveFileDialog saveFile = new SaveFileDialog();
                string ext = viewNhanXet.GetFocusedRowCellValue("cExt").ToString();
                saveFile.Filter = "FileType|*" + ext;
                if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileStream fs = new FileStream(saveFile.FileName, FileMode.OpenOrCreate, FileAccess.Write);
                    BinaryWriter br = new BinaryWriter(fs);
                    br.Write((byte[])viewNhanXet.GetFocusedRowCellValue("pNoiDung"));
                    fs.Dispose();
                }
            }
        }

        #endregion

        private void xtraTabControl1_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            if (txtMaThuyenVien.Text == "")
            {
                e.Cancel = true;
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewHoChieu.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblImmigrationCrewBindingSource.RemoveCurrent();
                    tblImmigrationCrewTableAdapter.Update(dsCrew.tblImmigrationCrew);
                    alertControl1.Show(this, "Thông báo", "Cập nhật thành công");
                }
            }
        }

        #region Experience

        private void lookVessel_EditValueChanged(object sender, EventArgs e)
        {

            //MessageBox.Show(((DataRowView)(tblVesselBindingSource.Current)).Row["nFlagId"].ToString());

            // ((DevExpress.XtraEditors.LookUpEdit)lookupFlag).EditValue = 
        }


        private void pictureEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void bandExp_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (bandExp.GetRowCellValue(e.RowHandle, "dDisembarkedDate").ToString() != "" && bandExp.GetRowCellValue(e.RowHandle, "dDisembarkedDate").ToString() != "")
            {
                float months = ((DateTime)bandExp.GetRowCellValue(e.RowHandle, "dDisembarkedDate")).Month - ((DateTime)bandExp.GetRowCellValue(e.RowHandle, "dEmbarkedDate")).Month;
                if (months == 0)
                    months = 1;
                bandExp.SetRowCellValue(e.RowHandle, "fDuration", months);
            }
            bandExp.SetRowCellValue(e.RowHandle, bandExp.Columns["nCrewId"], txtMaThuyenVien.EditValue.ToString());
        }


        private void btnxoa_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (bandExp.FocusedRowHandle > -1)
            {
                tblExprienceBindingSource.RemoveCurrent();

            }
        }
        #endregion

        private void xoaCertificate_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewCertificate.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblCertificateCrewBindingSource.RemoveCurrent();
                    tblCertificateCrewTableAdapter.Update(dsCrew.tblCertificateCrew);
                    alertControl1.Show(this, "Thông báo", "Cập nhật thành công");
                }
            }
        }
    }
}
